﻿// Copyright (c) Inossem. All rights reserved.
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using DWF.Studio.Custom;
using DWF.Studio.Host;
using DWF.Studio.ISerivces;
using DWF.Studio.NuGetManagement;
using DWF.Studio.Project;
using DWF.Studio.Services;
using DWF.Studio.Share.Log;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using WpfMessageBoxLibrary;

namespace DWF.Studio.Views
{
    /// <summary>
    /// 包详情页面
    /// </summary>
    public partial class UCtrlPackageDetail : UserControl
    {
        /// <summary>
        /// 包管理
        /// </summary>
        private IPackageManager _packageManager = null;

        /// <summary>
        /// 工程管理
        /// </summary>
        private ProjectManager _projectManager = null;

        /// <summary>
        /// 当前的选择nuget包
        /// </summary>
        private NugetPackageWrap _currentPackageWrap = null;

        /// <summary>
        /// 当前工程的依赖包
        /// </summary>
        private PackageInfo _dependencyPackageInfo = null;

        /// <summary>
        /// 处理更新版本时新的安装包和配置文件不一致问题 （没在方法里加是因为更新按钮刷新时异步安装按钮会闪）
        /// </summary>
        private IEnumerable<NuGetPackage> allPackagesWithCurrentName = null;
        /// <summary>
        /// 
        /// </summary>
        private IConfigService _configService = null;

        private IAppService _appService = null;
        public NugetPackageWrap selectionPackage = null;

        public UCtrlPackageDetail()
        {
            InitializeComponent();

            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                init();
            }
        }
        public void RefreshPage()
        {
            this.package_img.Source = null;
            init();
        }
        /// <summary>
        /// 初始化
        /// </summary>
        private void init()
        {
            _configService = new ConfigService();
            var config = _configService.LoadSysConfig();

            var packageUri = config.GetStablePackageUri();
            switch (WindowPackageManagement.packagePageStatus)
            {
                case PackagePageStatus.networkPackageShow:
                    _packageManager = new PackageManager(packageUri, GetPackageStatus.officialPackageSource);break;
                case PackagePageStatus.localPackageShow:
                    _packageManager = new PackageManager(packageUri, GetPackageStatus.localPackagesSource);break;
                case PackagePageStatus.customPackageShow:
                    _packageManager = new PackageManager(packageUri, GetPackageStatus.customPackageSource);break;
                case PackagePageStatus.packageSourceManagerShow:
                    _packageManager = new PackageManager(packageUri, GetPackageStatus.localPackagesSource);break;
                default:
                    _packageManager = new PackageManager(packageUri);break;
            }
            _projectManager = ProjectManager.Instance;
            _appService = AppService.Instance;

            this.refreshInfos();
        }
        /// <summary>
        /// 当前控件加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                GlobalActionHandler.PackageSelected += packageSelected;//注册
            }
        }
        /// <summary>
        /// 当前控件卸载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserControl_Unloaded(object sender, RoutedEventArgs e)
        {
            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                GlobalActionHandler.PackageSelected -= packageSelected;//注销
            }
        }
        /// <summary>
        /// 选择包
        /// </summary>
        /// <param name="e"></param>
        private async void packageSelected(TagEventArgs<NugetPackageWrap> e)
        {
            this.IsEnabled = false;
            try
            {
                _dependencyPackageInfo = null;
                this.refreshInfos();
                this.btnInstall.Visibility = Visibility.Visible;
                this.btnUpdate.Visibility = Visibility.Visible;
                var selectedPackaging = new object();
                _currentPackageWrap = e.Tag;
                
                if (_currentPackageWrap != null)
                {
                    bool _displayPackageButton = new bool();

                    this.tbId.Text = _currentPackageWrap.Id;//显示id
                    var dependencyPackages = _projectManager.GetDependOnPackageInfos();
                    if (dependencyPackages != null)
                    {
                        this.package_img.Source = new BitmapImage(new Uri("../Resources/Package/ProcessGoActivity.png", UriKind.Relative));
                        var dependecyPackage = dependencyPackages.FirstOrDefault(item => item.Id == _currentPackageWrap.Id);
                        if (WindowPackageManagement._currentPackageWrapList.Count > 0)
                        {
                            selectedPackaging = WindowPackageManagement._currentPackageWrapList.Where(item => item.Id == _currentPackageWrap.Id).FirstOrDefault();//返回当前包集合
                        }
                        else
                            selectedPackaging = null;

                        if (dependecyPackage != null)
                        {
                            _dependencyPackageInfo = dependecyPackage;
                            tbInstallVersion.Text = _dependencyPackageInfo.Version;//显示当前工程依赖的包版本
                            btnInstall.IsEnabled = true;
                            if (_dependencyPackageInfo.IsInstalled)//如果已安装 则显示卸载 
                            {
                                if (selectedPackaging == null)
                                {
                                    btnInstall.Content = LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_Button_Content_Uninstall");
                                    btnInstall.Tag = "uninstall";
                                    btnUpdate.Content = LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_Button_Content_Update");
                                    btnUpdate.Tag = "install";
                                }
                                else if (selectedPackaging != null && (selectedPackaging as NugetPackageWrap).PackageOperationType == PackageOperationType.Install)
                                {
                                    btnInstall.Content = LocalizationProvider.GetLocalizedString("MessageBox_Button_Cancel");
                                    btnInstall.Tag = "cancel";
                                    btnUpdate.IsEnabled = false;
                                    btnUpdate.Content = LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_Button_Content_Update");
                                    btnUpdate.Tag = "install";
                                    this.cbVersion.IsEnabled = false;
                                }
                                else if (selectedPackaging != null && (selectedPackaging as NugetPackageWrap).PackageOperationType == PackageOperationType.Update)
                                {
                                    btnInstall.Content = LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_Button_Content_Uninstall");
                                    btnInstall.Tag = "uninstall";
                                    btnInstall.IsEnabled = false;
                                    btnUpdate.Content = LocalizationProvider.GetLocalizedString("MessageBox_Button_Cancel");
                                    btnUpdate.Tag = "cancel";
                                    this.cbVersion.IsEnabled = false;
                                }
                                else if (selectedPackaging != null && (selectedPackaging as NugetPackageWrap).PackageOperationType == PackageOperationType.UnInstall)
                                {
                                    btnInstall.Content = LocalizationProvider.GetLocalizedString("MessageBox_Button_Cancel");
                                    btnInstall.Tag = "cancel";
                                    btnUpdate.IsEnabled = false;
                                    btnUpdate.Content = LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_Button_Content_Update");
                                    btnUpdate.Tag = "install";
                                    this.cbVersion.IsEnabled = false;
                                }
                            }
                            else//未安装 则显示安装
                            {
                                if (selectedPackaging == null)
                                {
                                    btnInstall.Content = LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_Button_Content_Install");
                                    btnInstall.Tag = "install";
                                    btnUpdate.IsEnabled = false;
                                    btnUpdate.Content = LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_Button_Content_Update");
                                    btnUpdate.Tag = "install";
                                }
                                else if ((selectedPackaging as NugetPackageWrap).PackageOperationType == PackageOperationType.Install)
                                {
                                    btnInstall.Content = LocalizationProvider.GetLocalizedString("MessageBox_Button_Cancel");
                                    btnInstall.Tag = "cancel";
                                    btnUpdate.IsEnabled = false;
                                    btnUpdate.Content = LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_Button_Content_Update");
                                    btnUpdate.Tag = "install";
                                    this.cbVersion.IsEnabled = false;
                                }
                                else if ((selectedPackaging as NugetPackageWrap).PackageOperationType == PackageOperationType.Update)
                                {
                                    btnInstall.Content = LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_Button_Content_Install");
                                    btnInstall.Tag = "install";
                                    btnInstall.IsEnabled = false;
                                    btnUpdate.Content = LocalizationProvider.GetLocalizedString("MessageBox_Button_Cancel");
                                    btnUpdate.Tag = "cancel";
                                    this.cbVersion.IsEnabled = false;
                                }
                                else if ((selectedPackaging as NugetPackageWrap).PackageOperationType == PackageOperationType.UnInstall)
                                {
                                    btnInstall.Content = LocalizationProvider.GetLocalizedString("MessageBox_Button_Cancel");
                                    btnInstall.Tag = "cancel";
                                    btnUpdate.IsEnabled = false;
                                    btnUpdate.Content = LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_Button_Content_Update");
                                    btnUpdate.Tag = "install";
                                    this.cbVersion.IsEnabled = false;
                                }
                            }
                            if (_currentPackageWrap.Version == dependecyPackage.Version)//如果版本相同 表示同一个包
                            {
                                var _currentPackageWrapId = _currentPackageWrap.Id;
                                _displayPackageButton = await this.displayPackageButton(selectedPackaging as NugetPackageWrap, dependecyPackage, _currentPackageWrapId);
                            }
                            else//表示相同id的不同版本包
                            {
                                _currentPackageWrap.IsProjectDependency = false;
                                _currentPackageWrap.IsInstalled = false;
                            }
                        }
                        else //如果不是项目依赖 则显示安装
                        {
                            if (selectedPackaging == null)
                            {
                                _currentPackageWrap.IsProjectDependency = false;
                                _currentPackageWrap.IsInstalled = false;

                                btnInstall.Content = LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_Button_Content_Install");
                                btnInstall.Tag = "install";
                                tbInstallVersion.Text = String.Empty;
                                btnUpdate.Content = LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_Button_Content_Update");
                                btnUpdate.Tag = "install";
                            }
                            else if ((selectedPackaging as NugetPackageWrap).PackageOperationType == PackageOperationType.Install)
                            {
                                btnInstall.Content = LocalizationProvider.GetLocalizedString("MessageBox_Button_Cancel");
                                btnInstall.Tag = "cancel";
                                btnUpdate.IsEnabled = false;
                                btnUpdate.Content = LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_Button_Content_Update");
                                btnUpdate.Tag = "install";
                                this.cbVersion.IsEnabled = false;
                            }
                            else if ((selectedPackaging as NugetPackageWrap).PackageOperationType == PackageOperationType.Update)
                            {
                                btnInstall.Content = LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_Button_Content_Install");
                                btnInstall.Tag = "install";
                                btnInstall.IsEnabled = false;
                                btnUpdate.Content = LocalizationProvider.GetLocalizedString("MessageBox_Button_Cancel");
                                btnUpdate.Tag = "cancel";
                                this.cbVersion.IsEnabled = false;
                            }
                        }
                    }
                    bool _loadPackageVersion = await this.loadPackageVersion(selectedPackaging as NugetPackageWrap);
                    if (_loadPackageVersion == true && _displayPackageButton == true)
                    { }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.ToString());
            }
            this.IsEnabled = true;
        }
        /// <summary>
        /// 选择不同版本
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CbVersion_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var package = this.cbVersion.SelectedItem as NugetPackageWrap;
            if (package != null)
            {
                this.tbAuthor.Text = package.Authors;
                this.tbAuthor.ToolTip = package.Authors;
                this.tbPublishedOn.Text = package.PublishedOn.HasValue ? package.PublishedOn.Value.ToString("D", this._appService.GetCurrentCultureInfo()) : String.Empty;
                this.tbPublishedOn.ToolTip = package.PublishedOn.HasValue ? package.PublishedOn.Value.ToString("D", this._appService.GetCurrentCultureInfo()) : String.Empty;
                this.tbDescription.Text = package.Description+ Environment.NewLine+ package.Tags;

                if (_dependencyPackageInfo != null && _dependencyPackageInfo.Version != package.Version)//是当前工程依赖，并且版本不同 显示更新
                {
                    if ((btnInstall.Tag?.ToString() == "install" || btnInstall.Tag?.ToString() == "uninstall") && (btnUpdate.Tag?.ToString() == "install" || btnUpdate.Tag == null))
                    {
                        btnUpdate.IsEnabled = true;
                        btnUpdate.Tag = "install";
                    }
                    else if (btnUpdate.Tag?.ToString() == "cancel")
                    {
                        btnUpdate.IsEnabled = true;
                        btnUpdate.Tag = "cancel";
                        btnInstall.IsEnabled = false;
                    }
                }
                else//
                {
                    btnUpdate.IsEnabled = false;
                }
            }
        }

        /// <summary>
        /// 安装包
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnInstall_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_currentPackageWrap != null && this.cbVersion.SelectedItem != null)
                {
                    Window parentWindow = Window.GetWindow(this);
                    
                    NugetPackageWrap _currentPackageAdd = null;
                    if (this.btnInstall.Tag.ToString() == "install")
                    {
                        if (_currentPackageWrap.IsProjectDependency)//如果是工程依赖 表示本地没有安装
                        {
                            _currentPackageAdd = _currentPackageWrap;
                            _currentPackageAdd.PackageOperationType = PackageOperationType.Install;
                            WindowPackageManagement._currentPackageWrapList.Add(_currentPackageAdd);//添加包集合
                            btnInstall.Content = LocalizationProvider.GetLocalizedString("MessageBox_Button_Cancel");
                            btnInstall.Tag = "cancel";

                            btnUpdate.IsEnabled = false;
                            this.cbVersion.IsEnabled = false;
                            
                        }
                        else //如果不是 则按选择的版本安装
                        {
                            _currentPackageAdd = this.cbVersion.SelectedItem as NugetPackageWrap;
                            _currentPackageAdd.PackageOperationType = PackageOperationType.Install;
                            WindowPackageManagement._currentPackageWrapList.Add(_currentPackageAdd);//添加包集合
                            btnInstall.Content = LocalizationProvider.GetLocalizedString("MessageBox_Button_Cancel");
                            btnInstall.Tag = "cancel";

                            btnUpdate.IsEnabled = false;
                            this.cbVersion.IsEnabled = false;
                        }
                    }
                    else if (this.btnInstall.Tag.ToString() == "uninstall")//卸载
                    {
                        _currentPackageAdd = _currentPackageWrap;
                        _currentPackageAdd.PackageOperationType = PackageOperationType.UnInstall;
                        WindowPackageManagement._currentPackageWrapList.Add(_currentPackageAdd);//添加包集合
                        btnInstall.Content = LocalizationProvider.GetLocalizedString("MessageBox_Button_Cancel");
                        btnInstall.Tag = "cancel";
                        btnUpdate.IsEnabled = false;
                        this.cbVersion.IsEnabled = false;
                    }
                    else if (this.btnInstall.Tag.ToString() == "cancel")//取消安装或卸载
                    {
                        _currentPackageAdd = WindowPackageManagement._currentPackageWrapList.Where(o => o.Id == _currentPackageWrap.Id && o.Version == _currentPackageWrap.Version).FirstOrDefault();
                        var package = this.cbVersion.SelectedItem as NugetPackageWrap;
                        if (package == null)
                        {
                            return;
                        }
                        this.cbVersion.IsEnabled = true;
                        if (_dependencyPackageInfo != null && _dependencyPackageInfo.Version != package.Version)//是当前工程依赖，并且版本不同 显示更新
                        {
                            if (btnUpdate.Tag.ToString() != "cancel")
                            {
                                btnUpdate.IsEnabled = true;
                                btnUpdate.Tag = "install";
                            }
                        }
                        else//
                        {
                            btnUpdate.IsEnabled = false;
                        }
                        if (_currentPackageAdd.PackageOperationType == PackageOperationType.Install || _currentPackageAdd.PackageOperationType == PackageOperationType.Update)
                        {
                            btnInstall.Content = LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_Button_Content_Install");
                            btnInstall.Tag = "install";
                        }
                        else if (_currentPackageAdd.PackageOperationType == PackageOperationType.UnInstall)
                        {
                            btnInstall.Content = LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_Button_Content_Uninstall");
                            btnInstall.Tag = "uninstall";
                        }
                        WindowPackageManagement._currentPackageWrapList.Remove(_currentPackageAdd);
                    }
                    GlobalActionHandler.PackageWrapPrechange?.Invoke(new TagEventArgs<NugetPackageWrap>(_currentPackageAdd));
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.ToString());
            }
            
        }
        /// <summary>
        /// 包更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnUpdate_Click(object sender, RoutedEventArgs e)
        {
            NugetPackageWrap _currentPackageAdd = null;
            if (_currentPackageWrap != null)
            {
                if (this.btnUpdate.Tag.ToString() == "install")
                {
                    Window parentWindow = Window.GetWindow(this);
                    _currentPackageAdd = this.cbVersion.SelectedItem as NugetPackageWrap; //根据选择的版本更新
                    _currentPackageAdd.ChoicePackageVersion = _currentPackageWrap.Version;
                    _currentPackageAdd.PackageOperationType = PackageOperationType.Update;
                    WindowPackageManagement._currentPackageWrapList.Add(_currentPackageAdd);//添加包集合
                    btnUpdate.Content = LocalizationProvider.GetLocalizedString("MessageBox_Button_Cancel");
                    btnUpdate.Tag = "cancel";
                    btnInstall.IsEnabled = false;
                    this.cbVersion.IsEnabled = false;
                }
                else if (this.btnUpdate.Tag.ToString() == "cancel")//取消更新
                {
                    _currentPackageAdd = _currentPackageWrap;
                    btnUpdate.Content = LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_Button_Content_Update");
                    btnUpdate.Tag = "install";
                    btnInstall.IsEnabled = true;
                    NugetPackageWrap selectNugetPackageWrap = WindowPackageManagement._currentPackageWrapList.Where(o => o.Id == (this.cbVersion.SelectedItem as NugetPackageWrap).Id && o.Version == (this.cbVersion.SelectedItem as NugetPackageWrap).Version).FirstOrDefault();
                    WindowPackageManagement._currentPackageWrapList.Remove(selectNugetPackageWrap);
                    this.cbVersion.IsEnabled = true;
                }
                GlobalActionHandler.PackageWrapPrechange?.Invoke(new TagEventArgs<NugetPackageWrap>(_currentPackageAdd));
            }
        }
        /// <summary>
        /// 包更改 变更单个包
        /// </summary>
        /// <param name="newPackage"></param>
        /// <param name="isUninstall"></param>
        private void packageChange(NugetPackageWrap newPackage, bool isSuccess, bool isUninstall = false)
        {
            try
            {
                WindowLoading.SetContent(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_UnloadDesignerCtrl"));
                GlobalActionHandler.PackageChanging?.Invoke(EventArgs.Empty);
                var loader = RemoteLoaderHost.GetCurrentInstance();
                if (loader != null)
                {
                    loader.Unload();//卸载控件程序域
                }
                WindowLoading.SetContent(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_LoadDesignerCtrl"));

                RemoteLoaderHost.CreateInstance(_projectManager.GetProjectProperties, _projectManager.GetDependOnPackageInfos());
                GlobalActionHandler.PackageChanged?.Invoke(EventArgs.Empty);

                WindowLoading.CloseWindow();

                if (isSuccess)
                {
                    if (!isUninstall) //如果是更新或者安装
                    {
                        newPackage.IsInstalled = true;
                        newPackage.IsProjectDependency = true;
                        packageSelected(new TagEventArgs<NugetPackageWrap>(newPackage));
                    }
                    else  //如果是卸载
                    {
                        newPackage.IsInstalled = false;
                        newPackage.IsProjectDependency = false;
                        packageSelected(new TagEventArgs<NugetPackageWrap>(newPackage));
                    }
                }
                else
                {
                    var msgProperties1 = new WpfMessageBoxProperties()
                    {
                        Button = MessageBoxButton.OK,
                        ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_OK"),
                        Image = MessageBoxImage.Warning,
                        Text = $"{newPackage.Id} {newPackage.Version}" + LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_MsgBox_Msg_ChangePackage"),
                        Title = LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_MsgBox_Caption_ChangePackage"),
                    };
                    Window owner = Window.GetWindow(this);
                    WpfMessageBox.Show(owner, ref msgProperties1);
                }
            }
            catch (Exception e)
            {
                LogHelper.Error(e.ToString());
            }
        }

        /// <summary>
        /// 刷新控件
        /// </summary>
        private void refreshInfos()
        {
            this.tbId.Text = String.Empty;

            this.tbInstallVersion.Text = String.Empty;
            this.btnInstall.Visibility = Visibility.Hidden;
            this.btnUpdate.Visibility = Visibility.Hidden;
            this.btnInstall.Content = String.Empty;
            this.btnInstall.IsEnabled = true;

            this.cbVersion.ItemsSource = null;
            this.btnUpdate.IsEnabled = false;
            this.cbVersion.IsEnabled = true;
            this.btnUpdate.Content = String.Empty;

            this.tbAuthor.Text = String.Empty;
            this.tbPublishedOn.Text = String.Empty;
            this.tbDescription.Text = String.Empty;
        }
        private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            ((Image)sender).Source = StaticResource.DefaultNugetImage;
        }
        /// <summary>
        /// 显示按钮
        /// </summary>
        /// <param name="selectedPackaging"></param>
        /// <param name="dependecyPackage"></param>
        private async Task<bool> displayPackageButton(NugetPackageWrap selectedPackaging, PackageInfo dependecyPackage, string _currentPackageWrapId)
        {
            try
            {
                allPackagesWithCurrentName = await _packageManager.GetPackagesWithAllVersionAsync(_currentPackageWrapId);
                var package = allPackagesWithCurrentName.Where(Item => Item.Version == dependecyPackage.Version).FirstOrDefault();//判断是否加载不到本地包
                if (package != null)
                {
                    if (_dependencyPackageInfo != null)
                    {
                        _currentPackageWrap.IsProjectDependency = true;
                        _currentPackageWrap.IsInstalled = _dependencyPackageInfo.IsInstalled;
                    }
                }
                else
                {
                    _currentPackageWrap.IsProjectDependency = true;
                    _currentPackageWrap.IsInstalled = false;
                    if (allPackagesWithCurrentName != null && allPackagesWithCurrentName.ToList().Count > 0)
                    {
                        this.cbVersion.ItemsSource = allPackagesWithCurrentName.Select(item => new NugetPackageWrap(item)).OrderByDescending(o => int.Parse(o.Version.Replace(".", "")));
                        this.cbVersion.SelectedIndex = 0;

                        var newPackageBest = allPackagesWithCurrentName.ToList().FirstOrDefault();
                        this.cbVersion.SelectedValue = newPackageBest;
                        this.cbVersion.SelectedItem = newPackageBest;
                        this.cbVersion.Text = newPackageBest.Version;
                        if (selectedPackaging == null)
                        {
                            btnInstall.Content = LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_Button_Content_Uninstall");
                            btnInstall.Tag = "uninstall";
                            btnUpdate.Content = LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_Button_Content_Update");
                            btnUpdate.Tag = "install";
                        }
                        else if (selectedPackaging != null && (selectedPackaging).PackageOperationType == PackageOperationType.Update)
                        {
                            btnInstall.Content = LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_Button_Content_Uninstall");
                            btnInstall.Tag = "uninstall";
                            btnUpdate.Content = LocalizationProvider.GetLocalizedString("MessageBox_Button_Cancel");
                            btnUpdate.Tag = "cancel";
                            this.cbVersion.SelectedValue = selectedPackaging;
                            this.cbVersion.SelectedItem = selectedPackaging;
                            this.cbVersion.Text = selectedPackaging.Version;
                        }
                        else if (selectedPackaging != null && (selectedPackaging).PackageOperationType == PackageOperationType.UnInstall)
                        {
                            btnInstall.Content = LocalizationProvider.GetLocalizedString("MessageBox_Button_Cancel");
                            btnInstall.Tag = "cancel";
                            btnUpdate.IsEnabled = false;
                            btnUpdate.Content = LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_Button_Content_Update");
                            btnUpdate.Tag = "install";
                            this.cbVersion.IsEnabled = false;
                        }
                    }
                }
                return true;
            }
            catch (Exception e)
            {
                LogHelper.Error(e.ToString());
                return false;
            }
            
        }
        /// <summary>
        /// 加载版本，异步调用防止卡UI
        /// </summary>
        private async Task<bool> loadPackageVersion(NugetPackageWrap selectedPackaging)
        {
            try
            {
                if (_currentPackageWrap.NuGetPackage == null)//如果包装类中未有nuget包 则加载这个包。项目依赖包是这个情况
                {
                    var nugetPackage = await _packageManager.GetPackageByIdAsync(_currentPackageWrap.Id, _currentPackageWrap.Version);
                    if (nugetPackage != null)
                    {
                        _currentPackageWrap.SetNuGetPackage(nugetPackage,false);
                    }
                }
                if (_currentPackageWrap.NuGetPackage != null)
                {
                    var allversions = await _packageManager.GetPackagesWithAllVersionAsync(_currentPackageWrap.NuGetPackage);//获取包的所有版本

                    if (allversions != null && allversions.Count > 0)
                    {
                        this.cbVersion.ItemsSource = allversions.Select(item => new NugetPackageWrap(item)).OrderByDescending(o => new Version(o.Version));//int.Parse(o.Version.Replace(".", "")));
                        this.cbVersion.SelectedIndex = 0;
                        if (selectedPackaging != null && selectedPackaging.Id == (this.cbVersion.SelectedItem as NugetPackageWrap).Id)
                        {
                            this.cbVersion.SelectedValue = selectedPackaging;
                            this.cbVersion.SelectedItem = selectedPackaging;
                            this.cbVersion.Text = selectedPackaging.Version;
                        }
                    }
                }
                return true;
            }
            catch (Exception e)
            {
                LogHelper.Error(e.ToString());
                return false;
            }
        }
    }
}
